/**
 * LeaveNote.js
 * 
 * @description :: TODO: You might write a short summary of how this model works
 *              and what it represents here.
 * @docs :: http://sailsjs.org/#!documentation/models
 */

module.exports = {

	attributes : {
		
		startTime : {
			type : 'date',
			required : true
		},
		
		endTime : {
			type : 'date',
			required : true
		},
		
		hours : {
			type : 'integer',
			required : true
		},
		
		reason : {
			type : 'text'
		},
		
		type : {
			model : 'LeaveType',
		},
		
		form : {
			model : 'Form',
			required : true
		},
		
		owner : {
			model : 'User',
			required : true
		},
	},
	
	afterDestroy: function(notes, cb){
		
		var count = notes.length;
		for (var i = 0; i < notes.length; i++) {
			Form.destroy(notes[i].form)
			.then(function (result) {
				count--;
				if(count == 0)cb();
			}).catch(function(err){
				sails.log.error(err);
				cb(err);
			});
		}
		
	},
	
	afterCreate: function(note, cb){
		
		Form.update(note.form.id, {'note':note.id})
		.then(function (form) {
			cb();
		}).catch(function(err){
			sails.log.error(err);
		});
		
	},
	
	beforeCreate: function(note, cb){
		note.startTime = new Date(note.startTime - (8 * 60 * 60 * 1000));
		note.endTime = new Date(note.endTime - (8 * 60 * 60 * 1000));
		cb();
	},

};
